import React from 'react';
import { connect } from 'dva';
import router from 'umi/router';

import { getPSITokenId } from '../../../utils/tokenId';

import { withStyles } from '@material-ui/core/styles';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import IconButton from '@material-ui/core/IconButton';

import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemText from '@material-ui/core/ListItemText';
import ListItemSecondaryAction from '@material-ui/core/ListItemSecondaryAction';

import LeftArrowIcon from '@material-ui/icons/KeyboardArrowLeft'
import RightArrowIcon from '@material-ui/icons/KeyboardArrowRight'

import Grid from '@material-ui/core/Grid';
import CssBaseline from '@material-ui/core/CssBaseline';
import { MuiThemeProvider } from '@material-ui/core/styles';
import mainTheme from '../../../theme/mainTheme';
import Button from '@material-ui/core/Button';
import LinearProgress from '@material-ui/core/LinearProgress';
import MenuIcon from '@material-ui/icons/Menu';
import MenuItem from '@material-ui/core/MenuItem';
import Menu from '@material-ui/core/Menu';

import styles from '../../../utils/pageLayout';

import CustomerQueryDialog from './CustomerQueryDialog';
import CustomerEditDialog from './CustomerEditDialog';

class CustomerListPage extends React.Component {
  state = {
    queryDialogOpen: false,
    editDialogOpen: false,
    anchorEl: null,
  }

  constructor(props) {
    super(props);

    if (!getPSITokenId()) {
      router.replace('/auth/login');
    }
  }

  componentDidMount = () => {
    const { dispatch, qc } = this.props;
    dispatch({ type: 'customerList/queryCustomerList', payload: { page: 1, qc } });
  }

  handleMenu = event => {
    this.setState({ anchorEl: event.currentTarget });
  };

  onQueryMenuItemClick = () => {
    this.setState({ anchorEl: null, queryDialogOpen: true });
  }

  render() {
    const { classes, page, totalPage, totalCount, list, loading } = this.props;
    const { queryDialogOpen, anchorEl, editDialogOpen } = this.state;

    return (
      <MuiThemeProvider theme={mainTheme}>
        <CssBaseline />
        <Grid container alignItems='flex-start' wrap='nowrap' direction='column' className={classes.r}>
          <Grid item className={classes.h}>
            <AppBar position='static'>
              <Toolbar>
                <IconButton className={classes.menuButton} onClick={() => { router.replace('/') }}>
                  <LeftArrowIcon color='inherit' />
                </IconButton>
                <Typography style={{ flex: 1 }} variant="title" color="inherit">
                  客户资料一览表
                </Typography>
                <IconButton onClick={this.handleMenu}>
                  <MenuIcon color='inherit' />
                </IconButton>
                <Menu
                  anchorEl={anchorEl}
                  anchorOrigin={{
                    vertical: 'top',
                    horizontal: 'right',
                  }}
                  transformOrigin={{
                    vertical: 'top',
                    horizontal: 'right',
                  }}
                  open={anchorEl !== null}
                  onClose={() => { this.setState({ anchorEl: null }) }}>
                  <MenuItem onClick={this.onQueryMenuItemClick}>查询</MenuItem>
                  <MenuItem onClick={this.onAddCustomer}>新增客户资料</MenuItem>
                  <MenuItem onClick={() => { router.push('/customer/category') }}>客户分类</MenuItem>
                </Menu>
              </Toolbar>
            </AppBar>
            <LinearProgress color='secondary' hidden={!loading} />
          </Grid>

          <Grid item className={classes.c}>
            <List>
              {
                list && list.map((it, index) => {
                  return <ListItem key={index} divider button data-id={it.id} onClick={this.onDetail}>
                    <ListItemText primary={it.name}
                      secondary={`编码: ${it.code} / 分类: ${it.categoryName}`} ></ListItemText>
                    <ListItemSecondaryAction>
                      <IconButton data-id={it.id} onClick={this.onDetail}>
                        <RightArrowIcon />
                      </IconButton>
                    </ListItemSecondaryAction>
                  </ListItem>
                })
              }
              {
                (list && list.length === 0) && <ListItem key={0}>没有客户资料</ListItem>
              }
            </List>
          </Grid>

          <Grid item className={classes.f}>
            {
              list.length > 0 &&
              <Grid container justify='space-around' alignItems='baseline'>
                <Button disabled={page === 1} onClick={this.gotoPrevPage}>上一页</Button>
                <div>{page}/{totalPage} - 共{totalCount}记录</div>
                <Button disabled={page === totalPage} onClick={this.gotoNextPage}>下一页</Button>
              </Grid>
            }
          </Grid>
        </Grid>
        <CustomerQueryDialog open={queryDialogOpen}
          onOK={this.onQuery}
          onCancel={() => { this.setState({ queryDialogOpen: false }) }} />
        <CustomerEditDialog open={editDialogOpen} add={true}
          onOK={() => { this.setState({ editDialogOpen: false }) }}
          onCancel={() => { this.setState({ editDialogOpen: false }) }} />
      </MuiThemeProvider>
    );
  }

  /**
   * 查询
   */
  onQuery = () => {
    this.setState({ queryDialogOpen: false });
  }

  /**
   * 客户资料详情
   */
  onDetail = (event) => {
    const id = event.currentTarget.getAttribute('data-id');
    const { dispatch } = this.props;
    dispatch({ type: 'customerList/queryCustomerInfo', payload: { id } });

    router.push('/customer/detail');
  }

  /**
   * 新增客户资料
   */
  onAddCustomer = () => {
    const { dispatch } = this.props;
    const entity = {
      id: '', categoryId: '', categoryName: '', code: '', name: '', address: '', addressReceipt: '',
      contact01: '', mobile01: '', tel01: '', qq01: '', contact02: '', mobile02: '', tel02: '', qq02: '',
      bankName: '', bankAccount: '', tax: '', fax: '', initReceivables: '', initReceivablesDT: '',
      warehouseId: '', warehouseName: '', note: ''
    };
    dispatch({ type: 'customerList/saveEntity', payload: { entity } });

    this.setState({ anchorEl: null, editDialogOpen: true });
  }

  gotoPrevPage = () => {
    const { page, qc, dispatch } = this.props;
    if (page === 1) {
      return;
    }

    dispatch({ type: 'customerList/queryCustomerList', payload: { page: page - 1, qc } });
  }

  gotoNextPage = () => {
    const { page, totalPage, qc, dispatch } = this.props;
    if (page === totalPage) {
      return;
    }

    dispatch({ type: 'customerList/queryCustomerList', payload: { page: page + 1, qc } });
  }
}

CustomerListPage.propTypes = {
};

function mapStateToProps(state) {
  // 在运行的时候，DVA会把其全局的model对象的state传过来
  // 通过namespace来获取不同的state
  // 客户资料的namespace是customerList
  // 这就是下面的代码是 state.customerList的原因
  const { list, totalPage, totalCount, page, qc } = state.customerList;

  // 返回的对象就是本Component的Props中和state相关的
  // 关于loading的说明
  // 这是DVA封装的用于提示数据正在加载中的一个bool标志
  // 该标志存在 state.loading.models.[namespace]中
  return {
    list, totalPage, totalCount, page, loading: state.loading.models.customerList, qc
  };
}

// connect是DVA把Model和Component关联起来的方法
// mapStateToProps，也就是把Model里面的state赋值给Component的props
// 这样state改变的时候，组件的props值也改变，从而UI展现的数据也变化
// this.props.dispatch会自动被DVA注入
// 通过this.props.dispatch就可以调用DVA Model里面的action
export default connect(mapStateToProps)(withStyles(styles)(CustomerListPage));
